package com.example.activemq_demo2.com.mmall;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @ClassName JmsConsumer
 * @Description TODO
 * @Author wushaopei
 * @Date 2019/12/23 22:25
 * @Version 1.0
 */
public class JmsConsumer_Topic_Persist {

    public static  final  String ACTIVEMQ_URL = "tcp://49.234.197.103:61616";
    public static  final  String TOPIC_NAME = "Topic_Persists";

    public static void main(String[] args) throws JMSException, IOException {

        System.out.println("*** z4");

        // 1 创建连接工厂，按照给定的url地址，采用默认和用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        // 2 通过连接工厂，获得连接Connection 并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.setClientID("z4");
        // 3 创建会话session
        // 两个参数，第一个叫事务，第二个叫签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 4 创建目的地（具体是队列还是主体topic）
        Topic topic = session.createTopic(TOPIC_NAME);
        // 5 持久化订阅者
        TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic,"remark....");
        // 6 启动
        connection.start();
        // 7 监听发布的生产，从而进行订阅
        Message message = topicSubscriber.receive();
        while (null != message){
            TextMessage textMessage = (TextMessage) message;
            System.out.println("*****收到的持久化Topic: "+ textMessage.getText());
            message = topicSubscriber.receive(5000L);
        }

        System.in.read(); // 保证控制台不灭
        session.close();
        connection.close();

    }
}
